package net.lahuobao.mall.controller.admin;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.org.apache.regexp.internal.RE;
import net.lahuobao.export.util.ExportFileUtil;
import net.lahuobao.mall.entity.admin.*;
import net.lahuobao.mall.entity.admin.resultmodel.MallProjectEmployee;
import net.lahuobao.mall.service.admin.*;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.exception.ConstraintViolationException;
import org.jeecgframework.core.util.ContextHolderUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.jeecgframework.core.beanvalidator.BeanValidators;

import javax.servlet.http.HttpSession;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.net.URI;
import org.springframework.http.MediaType;
import org.springframework.web.util.UriComponentsBuilder;

/**   
 * @Title: Controller
 * @Description: 油卡
 * @author zhangdaihao
 * @date 2016-10-11 13:44:41
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/mallShopCardruleController")
public class MallShopCardruleController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(MallShopCardruleController.class);

	@Autowired
	private MallShopCardruleServiceI mallShopCardruleService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private Validator validator;

	@Autowired
	private MallProjectServiceI mallProjectService;

	@Autowired
	private MallOilsupplierServiceI mallOilsupplierService;

	@Autowired
	private MallProductCategoryServiceI categoryService;

    @Resource
    private ExportFileUtil exportFileUtil;

    @Autowired
    private MallProjectUpdateLogServiceI logService;
	/**
	 * 油卡列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("net/lahuobao/mall/admin/mallShopCardruleList");
	}
	@RequestMapping(params = "view")
	public ModelAndView view(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("net/lahuobao/mall/admin/mallShopCardView");
		mv.addObject("cardno",request.getParameter("cardno"));
		List<MallShopCardruleQuery> mallShopCardruleList = mallShopCardruleService.getMallShopCardInfo(request.getParameter("cardno"));
		if(mallShopCardruleList!=null && mallShopCardruleList.size()>0) {
			MallShopCardruleQuery shopCard = mallShopCardruleList.get(0);
			mv.addObject("oli", shopCard.getSupplierName());
			mv.addObject("shopName", shopCard.getShopName());
			mv.addObject("productName", shopCard.getProductName());
			mv.addObject("projectName",shopCard.getProjectName());
			mv.addObject("projectUserName",shopCard.getProjectName());
		}
		return mv;
	}
	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		String accountNo = ResourceUtil.getSessionUserName().getUserName();
		Map<String, Object> map = getPageQueryMap(request, dataGrid);
		map.put("accountNo", accountNo);
		map.put("accountId",ResourceUtil.getSessionUserName().getId());
		MallCardRole role = mallProjectService.getUserCardRole(ResourceUtil.getSessionUserName().getId());
		if(role!=null && role.getCode()==1){
			map.put("view","");
		}else{
			map.put("view","all");
		}
		mallShopCardruleService.selectMallShopCardRule(map, dataGrid);
		TagUtil.datagrid(response, dataGrid);
	}

	@RequestMapping(params = "viewlog")
	public void viewlog(MallProjectUpdateLogEntity mallProjectUpdateLogEntity,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		Map map = getRequestParam(request);
		String page = request.getParameter("page");
		String rows = request.getParameter("rows");
		int num = Integer.valueOf(page)-1;
		int row = Integer.valueOf(rows);
		int offset = num*row;
		map.put("offset",offset);
		map.put("limit",row);
		map.put("isPage","true");
		DataGrid dg = mallProjectService.getMallProjectLog(map);
		dataGrid.setTotal(dg.getTotal());
		dataGrid.setResults(dg.getResults());

		TagUtil.datagrid(response, dataGrid);
	}


	/**
	 * 删除油卡
	 * 
	 * @return
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(MallShopCardruleEntity mallShopCardrule, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		//mallShopCardrule = systemService.getEntity(MallShopCardruleEntity.class, mallShopCardrule.getId());

		String message = mallShopCardrule.getIsdelete()?"油卡启用成功":"油卡禁用成功";
		String isDelete = mallShopCardrule.getIsdelete()?"0":"1";
		String sql = "update lahuobao.mall_shop_cardrule set isDelete="+isDelete + " where id="+mallShopCardrule.getId();
		//mallShopCardruleService.delete(mallShopCardrule);
		mallShopCardruleService.updateBySqlString(sql);
		systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		
		j.setMsg(message);
		return j;
	}


	/**
	 * 获取添加页面
	 *
	 * @return
	 */
	@RequestMapping(params = "saveview")
	public ModelAndView saveview(HttpServletRequest request) {
		return new ModelAndView("net/lahuobao/mall/admin/mallShopCardruleAdd");
	}

	/**
	 * 获取编辑页面
	 *
	 * @return
	 */
	@RequestMapping(params = "editview")
	public ModelAndView editview(HttpServletRequest request,@RequestParam("cardNos") String cardNos) {
		ModelAndView model = new ModelAndView("net/lahuobao/mall/admin/mallShopCardruleEdit");
		if(StringUtils.isNotEmpty(cardNos)){
			String[] rows = cardNos.split(",");
			List<MallShopCardruleQuery> mallShopCardruleList = mallShopCardruleService.getMallShopCardInfo(rows[0]);
			if(mallShopCardruleList!=null && mallShopCardruleList.size()>0){
				MallShopCardruleQuery mallShop = mallShopCardruleList.get(0);
				model.addObject("mallShopCardrule",mallShop);
				model.addObject("shopid",mallShop.getShopid());
				model.addObject("shopname",mallShop.getShopName());
				model.addObject("productname",mallShop.getProductName());
				model.addObject("productid",mallShop.getProductid());
				model.addObject("cardNos",cardNos);
			}

		}
		return model;
	}

	/*商家列表*/
	@RequestMapping(params = "mallshopdatagrid")
	public void mallShopDatagrid(MallShopEntity mallShopEntity, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(MallShopEntity.class, dataGrid);

		/*店铺名称*/
		if(StringUtil.isNotEmpty(mallShopEntity.getShopname())){
			cq.like("shopname", "%"+mallShopEntity.getShopname()+"%");
			mallShopEntity.setShopname(null);
		}
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, mallShopEntity, request.getParameterMap());
		this.mallShopCardruleService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 获取添加选择商品页面
	 *
	 * @return
	 */
	@RequestMapping(params = "productview")
	public ModelAndView productview(HttpServletRequest request,String shopname, Integer shopid) {
		try {
			shopname = URLDecoder.decode(shopname, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		request.setAttribute("shopname", shopname);
		request.setAttribute("shopid", shopid);
		List<MallOilsupplierEntity> mallOilsuppliers = mallOilsupplierService.loadAll(MallOilsupplierEntity.class);
		request.setAttribute("malloilsuppliers", mallOilsuppliers);
		return new ModelAndView("net/lahuobao/mall/admin/mallShopCardruleProductList");
	}

	/**
	 * 获取修改选择商品页面
	 *
	 * @return
	 */
	@RequestMapping(params = "productviewedit")
	public ModelAndView productviewEdit(HttpServletRequest request,Integer shopid,String cardlist,Integer productid) {
		try {
			MallShopEntity shop = systemService.get(MallShopEntity.class,shopid);
			MallProductEntity product = systemService.get(MallProductEntity.class,productid);
			request.setAttribute("shopname", shop.getShopname());
			request.setAttribute("productname",product.getProductname());
			request.setAttribute("shopid", shopid);
			request.setAttribute("productid", productid);
			String[] rows = cardlist.split(",");
			List<MallShopCardruleQuery> mallShopCardruleList = mallShopCardruleService.getMallShopCardInfo(rows[0]);
			if(mallShopCardruleList!=null && mallShopCardruleList.size()>0) {
				MallShopCardrule mall = mallShopCardruleService.getMallShopCardRule(rows[0]);
				MallShopCardruleQuery mallShop = mallShopCardruleList.get(0);
				request.setAttribute("curOil", mall.getOilsupplierid());
				request.setAttribute("curUserId", mallShop.getEmployeeId());
				request.setAttribute("curProjectId", mallShop.getProjectid());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		request.setAttribute("cardlist", cardlist);
		List<MallOilsupplierEntity> mallOilsuppliers = mallOilsupplierService.loadAll(MallOilsupplierEntity.class);
		request.setAttribute("malloilsuppliers", mallOilsuppliers);
		return new ModelAndView("net/lahuobao/mall/admin/mallShopCardruleProductListEdit");
	}


	/*获取商家的商品*/
	@RequestMapping(params = "productdatagrid")
	public void mallShopDatagrid(MallProductEntity mallProductEntity, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid, Integer type) {
		CriteriaQuery cq = new CriteriaQuery(MallProductEntity.class, dataGrid);

		//虚拟商品
		cq.eq("saletype", 2);
		cq.eq("shopid", mallProductEntity.getShopid());

		String cadeCode = null;
		ResourceBundle bundle = PropertyResourceBundle.getBundle("shopping");
		//油卡商品
		if(StringUtil.isNotEmpty(type) && type == 1){
			cadeCode = bundle.getString("oildProductCategoryCode");
		}
		//ETC卡商品
		if(StringUtil.isNotEmpty(type) && type == 2){
			cadeCode = bundle.getString("etcProductCategoryCode");
		}
		MallProductCategoryEntity productCategory = categoryService.selectByCode(cadeCode);
		cq.eq("productcategoryid", productCategory.getId());
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, mallProductEntity, request.getParameterMap());
		this.mallShopCardruleService.getDataGridReturn(cq, false);
		TagUtil.datagrid(response, dataGrid);
	}

	@RequestMapping(params = "save")
	@ResponseBody
	public AjaxJson save(MallShopCardruleEntity mallShopCardrule, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		try {
			mallShopCardrule.setCreateuserid(123456);
			mallShopCardruleService.save(mallShopCardrule);
			message = "生成成功！";
		}catch (ConstraintViolationException e){
			e.printStackTrace();
			j.setSuccess(false);
			message = "卡号已存在！";
		}catch (Exception e){
			e.printStackTrace();
			j.setSuccess(false);
			message = "系统异常！";
		}
		j.setMsg(message);
		return j;
	}

    @RequestMapping(params = "edit")
    @ResponseBody
    public AjaxJson edit(MallShopCardruleEntity mallShopCardrule, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        try {

            if(StringUtils.isNotEmpty(mallShopCardrule.getCardno())){
                String cardNos = mallShopCardrule.getCardno();
                String[] rows = cardNos.split(",");
                for(String row : rows){
					MallShopCardrule mallCardruleDB = mallShopCardruleService.getMallShopCardRule(row);
//					List<MallShopCardruleQuery> mallShopCardruleList = mallShopCardruleService.getMallShopCardInfo(rows[0]);
					if(mallCardruleDB!=null){
						Integer oldUserId = mallCardruleDB.getProjectuserid();
						Integer newUserId = mallShopCardrule.getProjectUserId();
						mallCardruleDB.setShopid(mallShopCardrule.getShopid());
                        if(mallShopCardrule.getProjectUserId()>-1) {
							mallCardruleDB.setProjectuserid(mallShopCardrule.getProjectUserId());
                        }
						mallCardruleDB.setOilsupplierid(mallShopCardrule.getOilsupplierid());
                        mallShopCardruleService.saveMallShopCardRule(mallCardruleDB);
						try { //添加又卡修改日志
							addModifyLog(row,ResourceUtil.getSessionUserName(),oldUserId,newUserId);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
                }
            }
            message = "修改成功！";
        }catch (ConstraintViolationException e){
            e.printStackTrace();
            j.setSuccess(false);
            message = "卡号已存在！";
        }catch (Exception e){
            e.printStackTrace();
            j.setSuccess(false);
            message = "系统异常！";
        }
        j.setMsg(message);
        return j;
    }

    private void addModifyLog(String cardNo,TSUser operator,Integer oldUserId,Integer newUserId){
		String dateString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		String logContent = "修改时间:" + dateString + "操作人:" + operator.getRealName();
		String log = "";
		MallProjectEmployee oldEmp = null;
		MallProjectEmployee newEmp = null;
		Integer logType=0;
		if(oldUserId==null && newUserId == null){
			return;
		}
		if(oldUserId==newUserId){
			return;
		}
		if(oldUserId!=null){
			oldEmp = getMallProjectEmp(oldUserId);
		}
		if(newUserId!=null){
			newEmp = getMallProjectEmp(newUserId);
		}
		if(oldEmp==null){
			if(newEmp!=null){
				log += "将关联项目组无修改为"+newEmp.getProjectName()
						+ "将关联项目人员无修改为" + newEmp.getRealName();
				logType=2;
			}
		}
		if(oldEmp!=null){
			if(newEmp==null){
				log += "将关联项目组" +oldEmp.getProjectName()+ "修改为无"
						+ "将关联项目人员"+ oldEmp.getRealName() + "修改为无" ;
				logType=2;
			}else{
				if(oldEmp.getProjectId()==newEmp.getProjectId()){
					log += "将关联项目人员"+ oldEmp.getRealName() + "修改为" + newEmp.getRealName() ;
					logType=1;
				}else{
					log += "将关联项目组" +oldEmp.getProjectName()+ "修改为"+ newEmp.getProjectName()
							+ "将关联项目人员"+ oldEmp.getRealName() + "修改为" + newEmp.getRealName() ;
					logType=2;
				}

			}
		}

		if(StringUtils.isNotEmpty(log)){
			mallProjectService.addMallLog(cardNo,operator.getId(),logType,logContent+log);
		}

	}

	private MallProjectEmployee getMallProjectEmp(Integer userId){
		Map map = new HashMap();
		map.put("employeeId",userId);
		List<MallProjectEmployee> emp = mallProjectService.getProjectEmployee(map).getResults();
		if(emp!=null && emp.size()==1){
			return emp.get(0);
		}
		return null;
	}

    /**
     * 油卡回收
     * @return
     */
    @RequestMapping(params = "oilcardrecoverylist")
    public ModelAndView orderlist(HttpServletRequest request) {
        return new ModelAndView("net/lahuobao/mall/admin/mallOilCardRecoveryList");
    }

    /**
     * easyui AJAX请求数据
     * @param request
     * @param response
     * @param dataGrid
     * @param
     */

    @RequestMapping(params = "oilcardrecoverydatagrid")
    public void orderDatagrid(MallOilCardRecovery mallOilCardRecovery, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        if(StringUtil.isNotEmpty(request.getParameter("createTime_begin"))){
            mallOilCardRecovery.setCreateStartTime(request.getParameter("createTime_begin"));
        }
        if(StringUtil.isNotEmpty(request.getParameter("createTime_end"))){
            mallOilCardRecovery.setCreateEndTime(request.getParameter("createTime_end"));
        }
        TagUtil.datagrid(response, pageDateGrid(mallShopCardruleService.selectOilCardRecovery(mallOilCardRecovery), dataGrid));
    }

    @RequestMapping(params = "oilcardrecoveryexport")
    public void middleExpenditureExport(MallOilCardRecovery mallOilCardRecovery, HttpServletRequest request, HttpServletResponse response,
                                        DataGrid dataGrid){
        exportFileUtil.setFileName("油卡回收报表", "xlsx");

        if(StringUtil.isNotEmpty(request.getParameter("createTime_begin"))){
            mallOilCardRecovery.setCreateStartTime(request.getParameter("createTime_begin"));
        }
        if(StringUtil.isNotEmpty(request.getParameter("createTime_end"))){
            mallOilCardRecovery.setCreateEndTime(request.getParameter("createTime_end"));
        }
        // 构造数据导出
        try {
            int page = 1;
            int rows = 1000;
            exportFileUtil.initExport(response);
            request.setAttribute("pageExport", "yes");
            request.setAttribute("page", page);
            request.setAttribute("rows", rows);
            int begin_ = exportFileUtil.exportIOStream(response, mallShopCardruleService.selectOilCardRecovery(mallOilCardRecovery), rows, page, 0);
            for(int i = 2; begin_ != page; i++ ){
                page = begin_;
                request.setAttribute("page", i);
                begin_ = exportFileUtil.exportIOStream(response, mallShopCardruleService.selectOilCardRecovery(mallOilCardRecovery), rows, begin_, 1);
            }
            exportFileUtil.finish(response);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 批量更新状态
     * @param ids
     * @param state
     * @return
     */
    @RequestMapping(params = "batchupstate")
    @ResponseBody
    public AjaxJson batchUpState(String ids, Integer state) {
        AjaxJson j = new AjaxJson();
        try {
            mallShopCardruleService.batchUpState(ids, state);
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("系统异常，请稍候再试！");
            e.printStackTrace();
        }finally {
            return j;
        }
    }

    /**
     * 油卡回收详情
     * @return
     */
    @RequestMapping(params = "detail")
    public ModelAndView detail(String id) {
        MallShopCardrule entity = mallShopCardruleService.selectById(Integer.valueOf(id));
        ModelAndView mv = new ModelAndView("net/lahuobao/mall/admin/mallOilCardDetail");
        //油卡信息
        mv.addObject("oilCard", entity);
        //变更信息
        List<MallProjectUpdateLogEntity> logs = logService.selectByOilCardNo(entity.getCardno());
        mv.addObject("logs", logs);
        return mv;
    }


    /**
     * 油卡消费记录
     * @return
     */
    @RequestMapping(params = "oilcarduse")
    public void oilCardUse(MallOilCardRecovery mallOilCardRecovery, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        if(StringUtil.isNotEmpty(request.getParameter("createTime_begin"))){
            mallOilCardRecovery.setCreateStartTime(request.getParameter("createTime_begin"));
        }
        if(StringUtil.isNotEmpty(request.getParameter("createTime_end"))){
            mallOilCardRecovery.setCreateEndTime(request.getParameter("createTime_end"));
        }
        List<MallOilCardRecovery> lists = mallShopCardruleService.selectOilCardRecoveryByCardNo(mallOilCardRecovery);
        TagUtil.datagrid(response, pageDateGrid(lists, dataGrid));
    }


    /**
     * 统计油卡使用情况
     * @return
     */
    @RequestMapping(params = "statistics")
    @ResponseBody
    public AjaxJson StatisticsOilCardRecoveryUse() {
        AjaxJson j = new AjaxJson();
        try {
            j.setObj(mallShopCardruleService.StatisticsOilCardRecoveryUse());
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("系统异常，请稍候再试！");
            e.printStackTrace();
        }finally {
            return j;
        }
    }

    /**
     * 详情导出
     * @param mallOilCardRecovery
     * @param request
     * @param response
     */
    @RequestMapping(params = "oilcarddetailexport")
    public void oilCardDetailExport(MallOilCardRecovery mallOilCardRecovery, HttpServletRequest request, HttpServletResponse response){
        exportFileUtil.setFileName("油卡使用详情报表", "xlsx");
        if(StringUtil.isNotEmpty(request.getParameter("createTime_begin"))){
            mallOilCardRecovery.setCreateStartTime(request.getParameter("createTime_begin"));
        }
        if(StringUtil.isNotEmpty(request.getParameter("createTime_end"))){
            mallOilCardRecovery.setCreateEndTime(request.getParameter("createTime_end"));
        }
        // 构造数据导出
        try {
            int page = 1;
            int rows = 1000;
            exportFileUtil.initExport(response);
            request.setAttribute("pageExport", "yes");
            request.setAttribute("page", page);
            request.setAttribute("rows", rows);
            int begin_ = exportFileUtil.exportIOStream(response, mallShopCardruleService.selectOilCardRecoveryByCardNo(mallOilCardRecovery), rows, page, 0);
            for(int i = 2; begin_ != page; i++ ){
                page = begin_;
                request.setAttribute("page", i);
                begin_ = exportFileUtil.exportIOStream(response, mallShopCardruleService.selectOilCardRecoveryByCardNo(mallOilCardRecovery), rows, begin_, 1);
            }
            exportFileUtil.finish(response);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

}
